<?php
class FeedItem
{
	/* This class will interface directly with the MySQL database, and provide methods for
	 * rendering feed items. It will not need to modify the contents of the feed item,
	 * although this functionality could be added at a later date if required.
	 */

	private $ID,
		$UID,
		$title,
		$content,
		$imageURL,
		$timestamp;

	public function __construct($ID,$new=false,$args=false)
	{
		//get item from Database. If new is true, ignore ID and make new feedItem using data in $args
		if($new==true)
		{
			$sql = "INSERT INTO feeditems (uid, title, content, imageurl, timestamp) VALUES(" . $args['uid'] . ", "  . $args['title'] . ", " . $args['content'] . ", " . $args['imageurl'] . ", " . $args['timestamp'] . ")";
			mysql_query($sql);
		}
		else
		{
			$sql = "SELECT * FROM feeditems WHERE id=" . $ID;
        	$result = mysql_query($sql);
        	$row = mysql_fetch_array($result, MYSQL_ASSOC)); 
			$this->UID = $row['uid'];
			$this->title = $row['title'];
			$this->content = $row['content'];
			$this->imageURL = $row['imageurl'];
			$this->timestamp = $row['timestamp'];	
		}
	}
	public function getTitle()
	{
		return $title;
	}
	public function getContent()
	{
		return $content;
	}
	public function getImage()
	{
		return $imageURL;
	}
	public function getSince()
	{
		$periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
    	$lengths = array("60","60","24","7","4.35","12","10");
    	$now = time();
   		$difference = $now - $this->timestamp;
		for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
        	$difference /= $lengths[$j];
    	}
		$difference = round($difference);
		if($difference != 1) {
        	$periods[$j].= "s";
    	}
		//returns a string like "1 day ago", "5 minutes ago" etc.
    	return "$difference $periods[$j] ago";
	}

	public function getHTML()
	{
		return "<div class='feeditem'>
		<img src='images/activityicon.png' alt=''>
		<h3>".$this->getTitle()."</h3>
		<p>".$this->getContent()."</p>
		<a href='".$this->getImage()."' class='imagelink'>".$this->getSince()."</a>
		</div>";
	}
}

?>